# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import csv
import os

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class ScdailyPipeline:
    def __init__(self):
        self.csv_file = 'sc_daily.csv'
        self.fieldnames = ['title', 'news', 'news_data', 'pic_link_list', 'news_link']  # 定义CSV列名

        # 如果文件不存在，写入表头
        if not os.path.exists(self.csv_file):
            with open(self.csv_file, 'w', newline='', encoding='utf-8-sig') as f:
                writer = csv.DictWriter(f, fieldnames=self.fieldnames)
                writer.writeheader()

    def process_item(self, item, spider):
        with open(self.csv_file, 'a', newline='', encoding='utf-8-sig') as f:
            writer = csv.DictWriter(f, fieldnames=self.fieldnames)
            writer.writerow(item)
        return item
